package com.mycompany.client;

import com.mycompany.client.states.ClientState;
import com.mycompany.client.states.RootJobState;
import com.mycompany.protocol.FlowState;
import com.mycompany.protocol.IntroduceCommand;
import com.mycompany.protocol.RootJobCommand;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author artyukhov
 */
public class ConnectedClient {

    private final String name;
    private final Socket clientSocket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private ClientState clientState;

    public ConnectedClient(String host, int port, String name) throws UnknownHostException, IOException {
        this.name = name;
        this.clientSocket = new Socket(host, port);
        out = new ObjectOutputStream(clientSocket.getOutputStream());
        in = new ObjectInputStream(clientSocket.getInputStream());
    }

    public void introduceToServer() throws IOException, ClassNotFoundException {
        IntroduceCommand command = new IntroduceCommand(name);
        out.writeObject(command);
        out.flush();

        clientState = new RootJobState();
    }

    public void listenServer() throws IOException, ClassNotFoundException {
        while (true) {
            Object recievedCommand = in.readObject();
            clientState.updateFrame(recievedCommand);
        }
    }

    public void closeResources() {
        try {
            out.close();
            in.close();
            clientSocket.close();
        } catch (IOException ex) {
        }
    }
}
